package com.xiongjie.humanTask.jobworker;

import com.xiongjie.humanTask.entity.FormField;
import com.xiongjie.humanTask.entity.TaskDataSerializer;
import com.xiongjie.humanTask.entity.TaskEntity;
import com.xiongjie.humanTask.service.PgService;
import io.vertx.core.json.JsonObject;
import io.zeebe.client.api.response.ActivatedJob;
import io.zeebe.client.api.worker.JobClient;
import io.zeebe.client.api.worker.JobHandler;

import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class HumanTaskJobWorker implements JobHandler {

    static List<String> SUPPORTED_FIELD_TYPES = Arrays.asList("string", "number", "boolean");
    TaskDataSerializer serializer = new TaskDataSerializer();
    PgService pgService;

    public HumanTaskJobWorker(PgService pgService) {
        this.pgService = pgService;
    }

    @Override
    public void handle(JobClient client, ActivatedJob job) {
        Map<String, String> customHeaders = job.getCustomHeaders();

        //可以添加一步：在heade设置一个属性variables,里面是该人工任务需要的变量名字，然后在在job中将其取出来，组成真正的variables

        JsonObject variables = new JsonObject(job.getVariables());

        TaskEntity entity = new TaskEntity();
        entity.setKey(job.getKey());
        entity.setTimestamp(Instant.now().toEpochMilli());
        entity.setVariables(job.getVariables());
        entity.setName(customHeaders.getOrDefault("name", job.getElementId()));
        entity.setDescription(customHeaders.getOrDefault("description", ""));

        //可以添加一步映射获取，bpmn文件中模版属性是key,然后在文件服务器中拿出该文件的内容字符串

        Optional.ofNullable(customHeaders.get("formFields"))
                .ifPresent(
                        formFields -> {
                            validateFormFields(formFields);
                            entity.setFormFields(formFields);
                        });
        entity.setTaskForm(customHeaders.get("taskForm"));
        entity.setAssignee(customHeaders.getOrDefault("assignee", variables.getString("assignee")));
        entity.setCandidateGroup(customHeaders.getOrDefault("candidateGroup", variables.getString("candidateGroup")));

        //将人工任务存储到数据库
        pgService.save(entity);
    }

    private void validateFormFields(String form) {
        final List<FormField> formFields = serializer.readFormFields(form);

        formFields.forEach(
                field -> {
                    if (field.getKey() == null) {
                        throw new RuntimeException("form-field must have a 'key'");
                    }

                    final String type = field.getType();
                    if (!SUPPORTED_FIELD_TYPES.contains(type)) {
                        throw new RuntimeException(
                                String.format(
                                        "type of form-field '%s' is not supported. Must be one of: %s",
                                        type, SUPPORTED_FIELD_TYPES));
                    }
                });
    }
}
